// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod msg_tag;
mod msg_queue;

pub use msg_tag::*;
pub use msg_queue::MsgQueue;
use ohmw_core::bincode::{DefaultEncoder, DefaultEncoderError, Encode};

pub fn serialize_msg<M: Encode + MsgTag>(msg: M) -> Result<Vec<u8>, DefaultEncoderError> {
    let mut encoder = DefaultEncoder::new();
    let mut buf = Vec::new();
    0.encode(&mut encoder, &mut buf)?;
    msg.to_ref_tagged().encode(&mut encoder, &mut buf)?;
    unsafe { (buf.len() as u32 - size_of::<u32>() as u32).encode_unchecked(&mut DefaultEncoder::new(), &mut buf) };
    Ok(buf)
}

pub fn serialize_command_msg(tag: &str) -> Result<Vec<u8>, DefaultEncoderError> {
    let data_size = (size_of::<u32>() + tag.len()) as u32;
    let mut encoder = DefaultEncoder::new();
    let mut buf = Vec::with_capacity(data_size as usize + size_of::<u32>());
    data_size.encode(&mut encoder, &mut buf)?;
    tag.encode(&mut encoder, &mut buf)?;
    Ok(buf)
}
